import "reflect-metadata";
import Koa from "koa";
import { useKoaServer } from "routing-controllers";
import bodyParser from "koa-bodyparser";
import { AppDataSource } from "./src/database";
import { router, swagger } from "./src/controllers";
import { getAuthorizationChecker } from "./src/common/CommonUtils";

import KoaLogger from "koa-logger";

const app = new Koa();
const HOST = Bun.env.HOST || 'localhost';
const PORT = Number(Bun.env.PORT || '3000');

app.use(bodyParser())
    .use(KoaLogger())
    .use(swagger({ exposeSpec: true }));

useKoaServer(app, {
    ...router,
    cors: true,
    authorizationChecker: async (action) =>
        !!(await getAuthorizationChecker(action)),
    currentUserChecker: getAuthorizationChecker,
});

console.time("Server boot");

AppDataSource.initialize()
    .then(() => {
        console.log("DataSource has been initialized!");
        app.listen(PORT, () => {
            console.log(`Server running at http://${HOST}:${PORT}`);
            console.log(`Swagger API served at http://${HOST}:${PORT}/docs`);
            console.timeEnd("Server boot");
        });
    })
    .catch((error) => console.error(error));